<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* @framework : Codeigniter Framework
*
* @author: fatangel26
*
*/
	class Product extends Admin_Controller
	{
		public function __construct()
		{
			parent::__construct();

            if(!$this->my_session->is_Admin())
            {
                redirect(base_url()."backend/auth/login");

                exit();
            }

            $this->load->model("backend/product_model", "MProduct", TRUE);
		}

        public function index()
        {
            $this->_data['title'] = 'Jewel | Danh sách sản phẩm';

            $data['products'] = $this->MProduct->select();

            if(!$data['products'])
            {
                $data['msg'] = 'Không có dữ liệu để hiển thị.';
            }

            $this->load->model("backend/menu_model", "MMenu", TRUE);

            $data['menus'] = $this->MMenu->getMenus();

            $this->_data['content'] = $this->load->view("backend/product/listproduct", $data, TRUE);

            $this->load->view("backend/layout", $this->_data);
        }//End function

        public function createproduct()
        {
            $this->_data['title'] = 'Jewel | Thêm sản phẩm';

            $this->load->model("backend/menu_model", "MMenu", TRUE);

            $data['menus'] = $this->MMenu->getMenus();

            /*Validate data*/
            $this->form_validation->set_rules('product_name', 'Tên sản phẩm', 'trim|required|xss_clean');
            $this->form_validation->set_rules('product_img', 'Đường dẫn ảnh', 'trim|xss_clean');
            $this->form_validation->set_rules('product_thumb', 'Đường dẫn thumbnail', 'trim|xss_clean');
            $this->form_validation->set_rules('product_price', 'Giá', 'trim|required|numeric|greater_than[-1]|xss_clean');
            $this->form_validation->set_rules('product_quantity', 'Số lượng', 'trim|required|numeric|greater_than[-1]|xss_clean');
            $this->form_validation->set_rules('product_des', 'Mô tả sản phẩm', 'trim');
            $this->form_validation->set_rules('product_title', 'Tiêu đề không dấu', 'trim|required|xss_clean');
            $this->form_validation->set_message('required','<span style="font-weight: bold">%s</span> không được để trống');
            $this->form_validation->set_message('greater_than','<span style="font-weight: bold">%s</span> phải lớn hơn 0');
            $this->form_validation->set_message('numeric','<span style="font-weight: bold">%s</span> phải là số');

            if($this->form_validation->run() == FALSE)
            {
                $data['msg'] = '';
            }
            else
            {
                $user = $this->native_session->userdata('admin');

                $count = 0;
                //NEED
                foreach($data['menus'] as $menu):
                    if($menu->menu_id == $this->input->post('product_categories', TRUE)):
                        $cate_slug = $menu->slug;
                        break;
                    endif;
                    unset($data['menus'][$count]);
                    $count++;
                endforeach;

                $strInsert = array(
                    'product_name'      => $this->input->post('product_name', TRUE),
                    'product_img'       => $this->input->post('product_img', TRUE),
                    'product_thumb'     => $this->input->post('product_thumb', TRUE),
                    'product_price'     => $this->input->post('product_price', TRUE),
                    'product_quantity'  => $this->input->post('product_quantity', TRUE),
                    'product_des'       => $this->input->post('product_des'),
                    'product_title'     => $this->input->post('product_title', TRUE),
                    'product_status'    => $this->input->post('product_status', TRUE),
                    'product_categories'=> $this->input->post('product_categories', TRUE),
                    'product_hightlight'=> $this->input->post('product_hightlight', TRUE),
                    'product_user_created'=> $user['username'],
                    'menu_slug'         => $cate_slug
                );

                $check = $this->MProduct->create($strInsert);

                if(!$check)
                {
                    $data['msg'] = 'Lỗi khởi tạo.';
                }
                else
                {
                    $this->native_session->set_flashdata('msg', 'Thêm sản phẩm thành công.');

                    redirect(base_url()."backend/product");

                    exit();
                }
            }

            $this->_data['content'] = $this->load->view("backend/product/createproduct", $data, TRUE);

            $this->load->view("backend/layout", $this->_data);
        }

        public function editproduct()
        {
            $this->_data['title'] = 'Jewel | Cập nhật sản phẩm';

            if(!$this->uri->segment(4) || $this->uri->segment(4) == '')
            {
                show_404();

                exit();
            }

            $product_id = $this->uri->segment(4);

            $data['product'] = $this->MProduct->select(array('product_id' => $product_id));

            if(!$data['product'])
            {
                $data['product'] = 'Không tồn tại sản phẩm này.';
            }
            else
            {
                $this->load->model("backend/menu_model", "MMenu", TRUE);

                $data['menus'] = $this->MMenu->getMenus();

                /*Validate data*/
                $this->form_validation->set_rules('product_name', 'Tên sản phẩm', 'trim|required|xss_clean');
                $this->form_validation->set_rules('product_img_edit', 'Đường dẫn ảnh', 'trim|xss_clean');
                $this->form_validation->set_rules('product_thumb_edit', 'Đường dẫn thumbnail', 'trim|xss_clean');
                $this->form_validation->set_rules('product_price', 'Giá', 'trim|required|numeric|greater_than[-1]|xss_clean');
                $this->form_validation->set_rules('product_price_sale', 'Giá', 'trim|required|numeric|greater_than[-1]|xss_clean');
                $this->form_validation->set_rules('product_quantity', 'Số lượng', 'trim|required|numeric|greater_than[-1]|xss_clean');
                $this->form_validation->set_rules('product_des', 'Mô tả sản phẩm', 'trim');
                $this->form_validation->set_rules('product_title', 'Tiêu đề không dấu', 'trim|required|xss_clean');
                $this->form_validation->set_message('required','<span style="font-weight: bold">%s</span> không được để trống');
                $this->form_validation->set_message('greater_than','<span style="font-weight: bold">%s</span> phải lớn hơn 0');
                $this->form_validation->set_message('numeric','<span style="font-weight: bold">%s</span> phải là số');

                if($this->form_validation->run() == FALSE)
                {
                    $data['msg'] = '';
                }
                else
                {
                   foreach($data['menus'] as $menu):
                        if($menu->menu_id == $this->input->post('product_categories', TRUE)):
                            $menu_slug = $menu->slug;
                            break;
                        endif;
                    endforeach;

                    $strUpdate = array(
                        'product_name'      => $this->input->post('product_name', TRUE),
                        'product_img'       => $this->input->post('product_img_edit', TRUE),
                        'product_thumb'     => $this->input->post('product_thumb_edit', TRUE),
                        'product_price'     => $this->input->post('product_price', TRUE),
                        'product_price_sale'     => $this->input->post('product_price_sale', TRUE),
                        'product_quantity'  => $this->input->post('product_quantity', TRUE),
                        'product_des'       => $this->input->post('product_des'),
                        'product_title'     => $this->input->post('product_title', TRUE),
                        'product_status'    => $this->input->post('product_status', TRUE),
                        'product_categories'=> $this->input->post('product_categories', TRUE),
                        'product_hightlight'=> $this->input->post('product_hightlight', TRUE),
                        'menu_slug'         => $menu_slug
                    );

                    $check = $this->MProduct->edit($product_id, $strUpdate);

                    if(!$check)
                    {
                        $data['msg'] = 'Lỗi cập nhật.';
                    }
                    else
                    {
                        //NEED CHECK//
                        if($this->input->post('product_image_edit') != $data['product']->product_img):
                            if(is_file($data['product']->product_img)):
                                @unlink($data['product']->product_img);
                            endif;
                        endif;

                        if($this->input->post('product_thumb_edit') != $data['product']->product_thumb):
                            if(is_file($data['product']->product_thumb)):
                                @unlink($data['product']->product_thumb);
                            endif;
                        endif;

                        $this->native_session->set_flashdata('msg','Cập nhật sản phẩm thành công.');

                        redirect(base_url()."backend/product");

                        exit();
                    }

                }//End else
            }//End else

            $this->_data['content'] = $this->load->view("backend/product/editproduct", $data, TRUE);

            $this->load->view("backend/layout", $this->_data);
        }


        public function uploadify()
        {
            $this->load->helper('uploadify');

    		$img_data = img_uploadify();

    		$size = getimagesize($img_data['full_path']);

            if($size[0] < 100 || $size[1] < 50 )
            {
                @unlink($img_data['full_path']);
                echo 1;
            }
            else
            {
                $img_data = array(
                    'file_name' => $img_data['file_name'],
                    'width'     => $size[0],
                    'height'    => $size[1],
                    'fullpath'  => $img_data['full_path']
                );

                echo json_encode($img_data);
            }
        }//End function uploadify

        public function processimg()
        {
            /*Load jCrop helper*/
            $this->load->helper('jcrop');

            $thumb_image = jcrop();

            $img_parts = pathinfo($thumb_image);

            $img_data = array(
                'img_name'  => $img_parts['basename']
            );

            echo  json_encode($img_data);
        }//End processimg

        public function rejectimg()
        {
             if(is_file($this->input->post('filepath')))
                @unlink($this->input->post('filepath'));
        }//End rejectimg

        public function delproduct()
        {
            if(!$this->uri->segment(4) || $this->uri->segment(4)=='')
            {
                $data['msg'] = 'Không tồn tại sản phẩm này';
            }
            else
            {
                $product_id = $this->uri->segment(4);

                $check = $this->MProduct->delete(array('product_id' => $product_id));

                if(!$check)
                    $this->native_session->set_flashdata('msg', 'Lỗi xoá');
                else
                    $this->native_session->set_flashdata('msg', 'Xoá sản phẩm thành công');
            }//End else
            redirect(base_url()."backend/product");
        }

        public function import_from_csv()
        {
            if(!isset($_POST['csvgo']))
            {
                $this->_data['title'] = 'Preview CSV Import';

                $data['csv'] = $this->MProduct->import_csv();

                $this->_data['content'] = $this->load->view("backend/product/previewcsv", $data, TRUE);

                $this->load->view("backend/layout", $this->_data);
            }
            else
            {
                $this->MProduct->csv2db();

                $this->native_session->set_flashdata('msg', 'Import dữ liệu thành công.');

                redirect(base_url()."backend/product");
            }


        }//End function import_from_csv
	}

/* End of file Product.php */
/* Location: ./controllers/backend/product.php */